// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#pragma once

#include <melon/unit.h>
#include <melon/futures/future.h>

namespace kumo::pollux {
    /// Simple wrapper around melon's promise to track down destruction of
    /// unfulfilled promises.
    template<class T>
    class PolluxPromise : public melon::Promise<T> {
    public:
        PolluxPromise() : melon::Promise<T>() {
        }

        explicit PolluxPromise(const std::string &context)
            : melon::Promise<T>(), context_(context) {
        }

        PolluxPromise(
            melon::futures::detail::EmptyConstruct,
            const std::string &context) noexcept
            : melon::Promise<T>(melon::Promise<T>::makeEmpty()), context_(context) {
        }

        ~PolluxPromise() {
            if (!this->isFulfilled()) {
                KLOG(WARNING) << "PROMISE: Unfulfilled promise is being deleted. Context: "
                        << context_;
            }
        }

        explicit PolluxPromise(PolluxPromise<T> &&other) noexcept
            : melon::Promise<T>(std::move(other)),
              context_(std::move(other.context_)) {
        }

        PolluxPromise &operator=(PolluxPromise<T> &&other) noexcept {
            melon::Promise<T>::operator=(std::move(other));
            context_ = std::move(other.context_);
            return *this;
        }

        static PolluxPromise makeEmpty(const std::string &context = "") noexcept {
            return PolluxPromise<T>(melon::futures::detail::EmptyConstruct{}, context);
        }

    private:
        /// Optional parameter to understand where this promise was created.
        std::string context_;
    };

    using ContinuePromise = PolluxPromise<melon::Unit>;
    using ContinueFuture = melon::SemiFuture<melon::Unit>;

    /// Equivalent of melon's makePromiseContract for PolluxPromise.
    static inline std::pair<ContinuePromise, ContinueFuture>
    makePolluxContinuePromiseContract(const std::string &promiseContext = "") {
        auto p = ContinuePromise(promiseContext);
        auto f = p.getSemiFuture();
        return std::make_pair(std::move(p), std::move(f));
    }
} // namespace kumo::pollux
